import { getButtonMenus } from '@/api/ik/tureData/data.js'
import store from '@/store/index'

// 格式化层叠数据
/*
params:
data:Array
*/
export function initTableData(data) {
  function a(pre, obj) {
  // 全部 value 将扁平到此对象中
    const singleObj = {}

    // 递归处理的函数映射集
    const process = {
      String(prefix, obj) {
        singleObj[prefix] = obj
      },
      Array(prefix, obj) {
        obj.forEach((i, index) => {
          process[typeOf(i)](`${index}`, i)
        })
      },
      Object(prefix, obj) {
        for (const i in obj) {
          process[typeOf(obj[i])](`${prefix}` + `${i}`, obj[i])
        }
      },
      Number(prefix, obj) {
        singleObj[prefix] = obj
      },
      Undefined() {},
      Null() {}
    }

    function typeOf(obj) {
      return Object.prototype.toString.call(obj).slice(8, -1)
    }
    process[typeOf(obj)](pre, obj)
    return singleObj
  }
  for (const i in data) {
    data[i] = a('', data[i])
  }
  return data
}
// 计算外部url图片大小
export function getImgSize(url) {
  return new Promise((resolve, reject) => {
    const imgObj = new Image()
    imgObj.src = url
    imgObj.onload = () => {
      resolve({
        width: imgObj.width,
        height: imgObj.height
      })
    }
  })
}

// 计算地图坐标定位百分比
export function getPositionPercent(imgWith, imgHeight, localtioonX, localtioonY) {
  const x = localtioonX / imgWith
  const y = localtioonY / imgHeight

  return {
    left: Number.parseFloat(x).toFixed(4) * 100 + '%',
    bottom: Number.parseFloat(y).toFixed(4) * 100 + '%'
  }
}
// 获取菜单权限  参数为url
export function getButtons(menuCode, url) {
  return new Promise((resolve, reject) => {
    if (!menuCode && url) {
      for (const item of store.state.user.startMenus) {
        if (item.url === url) {
          menuCode = item.code
          break
        }
      }
    }
    console.debug(store.state.user, 'store.state.user')

    console.debug(menuCode, 'urlCode')
    console.debug(store.state.user.roleCode, 'store.state.user.roleCode')
    getButtonMenus(store.state.user.token, menuCode, store.state.user.roleCode).then(res => {
      const buttonlist = []
      const buttonInfo = []
      if (res[0]?.listMenuFun) {
        for (const item of res[0].listMenuFun) {
          buttonlist.push({ btnTitle: item.btnTitle, btnEvent: item.btnEvent })
        }
      }
      if (res[0]?.infoMenuFun) {
        for (const item of res[0].infoMenuFun) {
          buttonInfo.push({ btnTitle: item.btnTitle, btnEvent: item.btnEvent })
        }
      }
      const data = {
        buttonlist: buttonlist,
        buttonInfo: buttonInfo
      }
      resolve(data)
    }).catch(err => {
      reject(err + '失败')
    })
  })
}
